package com.iwhalecloud.bss.kite.cucc.service.attr.handler;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInstFunc;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.attr.handler.AbstractAttrHandler;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 *
 */
public class AppointRenewalPlanHandler extends AbstractAttrHandler<KiteProdInst, AttrData> {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    IOperateSceneInstService operateSceneInstService;

    @Override
    public void onShow(KiteAttr attr, KiteProdInst inst, AttrData data) {

        // 处理指定续约计划下拉值，从当前实例下获取已经创建好的资费计划
        List<KiteProdInstFunc> kiteProdInstFuncs = querySceneInstService
            .listProdInstFuncsByProdId(data.getCustId(), inst.getProdInstId(), LocalKeyConsts.FUNC_PROD_ID_ZF);
        if (KiteListUtils.isEmpty(kiteProdInstFuncs)) {
            kiteProdInstFuncs = querySceneInstService
                .listProdInstFuncsByProdId(data.getCustId(), inst.getProdInstId(), LocalKeyConsts.FUNC_PROD_ID_NBZF);
        }
        if (KiteListUtils.isEmpty(kiteProdInstFuncs)) {
            kiteProdInstFuncs = querySceneInstService
                .listProdInstFuncsByProdId(data.getCustId(), inst.getProdInstId(), LocalKeyConsts.FUNC_PROD_ID_5GZF);
        }
        if (KiteListUtils.isEmpty(kiteProdInstFuncs)) {
            kiteProdInstFuncs = querySceneInstService
                .listProdInstFuncsByProdId(data.getCustId(), inst.getProdInstId(), LocalKeyConsts.FUNC_PROD_ID_YF5GZF);
        }
        if (KiteListUtils.isEmpty(kiteProdInstFuncs)) {
            kiteProdInstFuncs = getBaseNewFuncProd(data);
        }
        if (!KiteListUtils.isEmpty(kiteProdInstFuncs)) {

            kiteProdInstFuncs = kiteProdInstFuncs.stream().filter(t -> !ActionType.D.equals(t.getActionType()))
                .collect(Collectors.toList());
            List<KiteAttrValue> attrValues = new ArrayList<>();

            kiteProdInstFuncs.forEach(funcProdInst -> {
                // 200003698 资费计划名称

                KiteAttr nameAttr = funcProdInst.getAttr("200004129");

                if (Objects.nonNull(nameAttr)) {
                    KiteAttrValue attrValue = new KiteAttrValue();
                    attrValue.setAttrId(attr.getAttrId());
                    attrValue.setAttrNbr(attr.getAttrNbr());
                    attrValue.setAttrValue(nameAttr.getValue());
                    attrValue.setAttrValueName(nameAttr.getValue());
                    attrValues.add(attrValue);
                }

            });
            attr.setAttrValues(attrValues);

            if (!KiteListUtils.isEmpty(attrValues) && !attrValues.stream().anyMatch(attrValue1 -> KiteStringUtils.equals(attrValue1.getAttrValue(), attr.getValue()))) {
                attr.setValue(attrValues.get(0).getAttrValue());
                attr.setValueDesc(attrValues.get(0).getAttrValue());
            }

        }
        else {
            attr.setValue("");
            attr.setValueDesc("");
            attr.setAttrValues(new ArrayList<>());

        }

        operateSceneInstService.setAttr(data.getSceneInstId(), inst.getInstType(), inst.getInstId(), attr);

    }

    private List<KiteProdInstFunc> getBaseNewFuncProd(AttrData data) {
        List<KiteProdInstFunc> zfKiteProdInstFuncs = Lists.newArrayList(); // 取所有接入类产品
        List<KiteProdInst> kiteProdInstList = querySceneInstService.listProdInsts(data.getSceneInstId());
        final KiteProdInst[] prodInsts = new KiteProdInst[1];
        List<KiteProdInst> prodInstList = Lists.newArrayList();
        String zfStr = DcPublicCache.getCodea("202012170001","zf_base_inst");
        if (KiteListUtils.isNotEmpty(kiteProdInstList)) {
            kiteProdInstList.stream().forEach(prodInst -> {
                List<KiteProdInstFunc> kiteProdInstFuncs = querySceneInstService
                    .listProdInstFuncs(data.getCustId(), prodInst.getProdInstId());
                if (KiteListUtils.isNotEmpty(kiteProdInstFuncs)) {
                    kiteProdInstFuncs.stream().forEach(kiteProdInstFunc -> {
                        if (KiteStringUtils.indexOf(zfStr, kiteProdInstFunc.getProdId())>-1) {
                            prodInstList.add(prodInst);
                        }
                    });
                }
            });
        }
        if (KiteListUtils.isNotEmpty(prodInstList)) {
            String[] str = zfStr.split("/");
            for (KiteProdInst kiteProdInst : prodInstList) {
                List<KiteProdInstFunc> kiteProdInstFuncList = new ArrayList<>();
                for(String prodId : str){
                    kiteProdInstFuncList = querySceneInstService
                        .listProdInstFuncsByProdId(data.getCustId(), kiteProdInst.getProdInstId(), prodId);
                    if(KiteListUtils.isNotEmpty(kiteProdInstFuncList)){
                        zfKiteProdInstFuncs.addAll(kiteProdInstFuncList);
                    }
                }
            }
        }
        zfKiteProdInstFuncs = zfKiteProdInstFuncs.stream().filter(distinctByKey(b -> b.getProdInstId())).collect(Collectors.toList());
        return zfKiteProdInstFuncs;
    }

    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        ConcurrentHashMap<Object, Boolean> map = new ConcurrentHashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

}
